import json
import os
from config import BASE_PATH

"""
    # File       : read_file.py
    # Time       ：2023/10/12 13:51
    # Author     ：曾伟雄
    # version    ：V1.0.0
    # Description：读取文件工具类
"""


class ReadFile():

    # 读取json文件
    @classmethod
    def read_file(cls,file_name, need_key):
        filePath = BASE_PATH + os.sep + 'data' + os.sep + file_name
        with open(filePath, mode='r', encoding='utf-8') as f:
            json_data = json.load(f)
            # print(json_data) # => [[],[],[],[]] 或者 ["","",""]
            list_data = []
            # 获取列表
            value = json_data.get(need_key)
            # 遍历列表，数据转元组
            for data in value:
                list_data.append([data])
                # list_data.append(data)
            return list_data

    # 写入json文件
    @classmethod
    def write_file(cls,origin_file_name, target_file_name):
        # 读取data.txt
        filePath = BASE_PATH + os.sep + 'data' + os.sep + origin_file_name
        target_filePath = BASE_PATH + os.sep + 'data' + os.sep + target_file_name
        all_data = []
        with open(filePath, mode='r', encoding='utf-8') as f:
            # 推导式去除每条数据尾部的换行符
            all_data = [line.strip() for line in f.readlines()]
        # 写入json
        json_data = {'timeout_30': []}
        for data in all_data:
            json_data['timeout_30'].append(data)
        # print(json_data)
        with open(target_filePath, mode='w', encoding='utf-8') as f:
            json.dump(json_data, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    # 生成参数化需要的json文件
    ReadFile().write_file('data.txt','sniffing.json')
    # 读取参数化数据
    # data = ReadFile().read_file('sniffing.json','timeout_30')
    # print(data)
